function [mx,sx] = histnorm(X,M,opt)

%HISTNORM  Histogram and normal distribution plot
%
%   [mx,sx] = histnorm(X) bins the elements of X into 10 equally spaced 
%   containers, returns the mean and standard deviation of the elements
%   of X thata are numbers (i.e., non-Inf and non-NaN), and produces a 
%   histogram bar plot of the results.
%
%   [mx,sx] = histnorm(X,M), where M is a scalar, uses M bins.
% 
%   [mx,sx] = histnorm(X,M,opt), where opt is a non-empty data, shows
%   mx and sx as a box in the plot.
%
%   See also hist, histc.

% G. Teza, 2007.

if nargin < 1
    error('Not enough input data'); 
end
if nargin < 2
    M = 10; 
end
if nargin < 3
    opt = []; 
end

lx = length(X);
[mx,sx] = meannum(X);

[N,xv]  = hist(X,M);

mn = max(N);

hist(X,M);

F = sum(N)*(xv(end)-xv(1))/(M-1);

hold on;
xc = linspace(xv(1),xv(end));
yc = F/(sqrt(2*pi)*sx)*exp(-(xc-mx).^2/(2*sx^2)); % magnified Gaussian
plot(xc,yc,'r','linewidth',2);
hold off;

if ~isempty(opt)
    hold on
    mstri = sprintf('MEAN: %10.3f',mx);
    sstri = sprintf('STD : %10.3f',sx);
    text(xv(1),0.95*mn,mstri);
    text(xv(1),0.85*mn,sstri);
    hold off;
end